<template>
	<div class="app-container">
		<el-button class="top-left" type="danger" @click="backRoom">返回</el-button>
		<div class="popup-panel" v-if="fileUpload">
			<el-row :gutter="50">
				<!-- <el-col :span="5">
					<el-upload class="upload-demo" ref="iupload" action="http://localhost:9081/common/upload"
						:on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple
						:limit="3" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :headers="headers"
						accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.pdf" :before-upload="handleBeforeUpload"
						:file-list="fileList">
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-col>
				<el-col :span="19">
					<label for="">选择文件接收人员</label>
					<el-table ref="multipleTable" :data="userList" @selection-change="handleSelectionChange"
						@select="UserSelect" @select-all="UserSelectAll" max-height="700" :row-key="getRowKey">
						<el-table-column type="selection" width="50" align="center" :reserve-selection="true" />
						<el-table-column label="用户名称" align="center" key="userName" prop="userName"
							:show-overflow-tooltip="true" />
						<el-table-column label="用户昵称" align="center" key="nickName" prop="nickName"
							:show-overflow-tooltip="true" />
						<el-table-column label="部门" align="center" key="deptName" prop="dept.deptName"
							:show-overflow-tooltip="true" />
						<el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
						<el-table-column label="备注" align="center" key="remark" prop="remark" />
					</el-table>
					<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
						:limit.sync="queryParams.pageSize" @pagination="getUserList" style="margin: 0 auto;" />
					</el-form>
				</el-col> -->
				<el-input v-model="toptitle" placeholder="请输入文件标题"  style="margin:0 20px ;width: calc(100% - 40px);"/>
				<my-editor style="margin: 20px;" ref="myEditor"></my-editor>
			</el-row>
			<div style="display: flex;justify-content: center;">
				<el-button type="danger" @click="(fileUpload = false)">查看资料</el-button>
				<el-button type="success" @click="dxqf">上传资料</el-button>
			</div>
		</div>
		<div class="popup-panel" v-else>
			<div class="file-list">
				<!-- <div v-for="(arrs,key) in myGroupFileList" :key="key">
					<div class="item" v-for="(item,key) in arrs" :key="key">
						<span> {{item.filename|| '暂无名称'}}</span>
						<el-button type="primary" @click="doDownload(item.filepath)">查看</el-button>
					</div>
				</div> -->
				<el-label name="1">{{panelTitle}}</el-label>
				 <el-table
				      :data="tableData"
				      style="width: 100%">
				      <el-table-column
				        prop="remark"
				        label="标题"
						width="300"
						algin="center"
				        >
				      </el-table-column>
					  <el-table-column
					    prop="nickName"
					    label="发布人">
					  </el-table-column>
					  <el-table-column
					    prop="createTime"
					    label="发布时间">
					  </el-table-column>
					   <el-table-column
					        fixed="right"
					        label="操作"
					        >
					        <template slot-scope="scope">
					          <el-button
					            @click.native.prevent="detailRow(scope.$index, content)"
					            type="text"
					            size="small">
					            查看详情
					          </el-button>
							  <el-button
							    @click.native.prevent="deleteRow(scope.$index,scope.row)"
							    type="text"
							    size="small">
							    删除
							  </el-button>
					        </template>
					      </el-table-column>
				    </el-table>
			</div>
			<div style="display: flex;justify-content: center;">
				<el-button type="success" @click="(fileUpload = true)">新增资料</el-button>
			</div>
		</div>
		<el-dialog title="文件详情" :visible.sync="filePanel" width="70%">
			<div style="height:58vh;overflow-x: hidden;">
				<div v-html="fileInfo"></div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="danger" @click="(filePanel = false)">取 消</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import {
		addGroupfiles,
		listGroupfiles,
		delGroupfiles
	} from "@/api/system/groupfiles";
	import {
		listUser
	} from "@/api/system/user";
	import {
		addMeeting
	} from "@/api/system/meeting";
	import {
		addSendsms
	} from "@/api/system/sendsms";
	import {
		getToken
	} from "@/utils/auth";
	import MyEditor from '@/components/mentionModel/MyEditor.vue'
	export default {
		components: {
		  MyEditor,
		},
		data() {
			return {
				toptitle:null,
				typeKey:'',
				panelTitle:'',
				tableData:[],
				filePanel:false,//弹出层
				fileInfo:null,//返显富文本
				content:"tuieditor富文本编辑器初始值",
				myGroupFileList: [], //可下载文件列表
				fileUpload: false,
				fileList: [], //文件列表
				smsInfo: {
					status: 0,
					masterId: 0,
					smsContent: "",
					beginTime: "",
					receiveMembers: "",
				},
				dxVisible: false, //发短信的弹出层
				hyVisible: false, //创建会议的弹出层
				form: {},
				info: {
					realName: "张三",
					name: "未命名",
					time: "2022-05-03 10:00:00 - 13:00:00",
					id: "123456789",
				},
				treeData: [],
				defaultProps: {
					children: "children",
					label: "label",
				},
				currentCheckData: {}, // 当前选中的值
				userList: [],
				total: 0,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					userName: undefined,
					phonenumber: undefined,
					status: undefined,
					deptId: undefined,
				},
				selected_user_nums: [], //电话号码
				selected_user_ids: [], //人员id
				meetingInfo: {
					status: 0,
					masterId: 0,
					meetingName: "",
					beginTime: "",
					meetingRoomId: "",
					meetingMembers: "",
				},
				deptId: -1,
				headers: {
					Authorization: "Bearer " + getToken(),
				},
				groupfile: {
					filename: "",
					filepath: "",
					phonenumbers: "",
					userids: "",
					usernames: "",
					content:""
				},
				fileType: ["doc", "docx", "xls", "xlsx", "pptx", "ppt", "txt", "pdf", 'png', 'jpg', 'jpeg']
			};
		},
		computed: {
			...mapGetters(["userId"]),
			...mapGetters(["userObj"]),
		},
		created() {
			this.loadTreedata();
			console.log(this.$route.query)
			this.panelTitle = this.$route.query.name
			this.typeKey = this.$route.query.key
			let deptId = this.$route.query.dept;
			this.fileUpload = this.$route.query.files
			this.queryParams.deptId = deptId
			this.deptId = deptId
			this.getUserList();
			this.getMyGroupFileList()
		},
		methods: {
			deleteRow(index,data){
				delGroupfiles(data.id).then(res=>{
					if(res.code == 200){
						this.$message.success(res.msg)
						this.getMyGroupFileList()
					}else{
						this.$message.error(res.msg)
					}
					console.log(res)
				})
			},
			detailRow(index,data){
				console.log(index)
				console.log(data)
				console.log(this.tableData[index])
				this.filePanel = true
				this.fileInfo = this.tableData[index].content
				console.log(this.fileInfo)
			},
			getRowKey(row) {
				return row.phonenumber
			},
			toggleSelection() {
				for (let b = 0; b < this.userList.length; b++) {
					for (let i = 0; i < this.selected_user_nums.length; i++) {
						if (this.userList[b].phonenumber == this.selected_user_nums[i]) {
							console.log('选中')
							this.$refs.multipleTable.toggleRowSelection(this.userList[b]);
						}
					}
				}
			},
			doDownload(url) {
				
				this.filePanel = true;
				
				console.log('down load')
				console.log(url)
				// this.$electron.ipcRenderer.send("downloadVideo", url)
			},
			getMyGroupFileList() {
				listGroupfiles({filename:this.typeKey}).then((res) => {
					console.log(res)
					this.myGroupFileList = []
					this.tableData = []
					const rows = res.rows
					this.tableData = res.rows
					// rows.forEach((item) => {
					// 	const filenames = item.filename.split(",")
					// 	const filepaths = item.filepath.split(",")
					// 	let len = filenames.length
					// 	let tmp = []
					// 	for (let i = 0; i < len; i++) {
					// 		tmp.push({
					// 			filename: filenames[i],
					// 			filepath: process.env.VUE_APP_BASE_API + filepaths[i]
					// 		})
					// 	}
					// 	this.myGroupFileList.push(tmp)
					// })
					console.log(this.tableData)
				})
			},
			// 上传前校检格式和大小
			handleBeforeUpload(file) {
				// 校检文件类型
				if (this.fileType) {
					let fileExtension = "";
					if (file.name.lastIndexOf(".") > -1) {
						fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
					}
					const isTypeOk = this.fileType.some((type) => {
						if (file.type.indexOf(type) > -1) return true;
						if (fileExtension && fileExtension.indexOf(type) > -1) return true;
						return false;
					});
					if (!isTypeOk) {
						// this.$modal.msgError();
						this.$message({
							message: `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`,
							type: "warning",
						});
						return false;
					}
				}
				// // 校检文件大小
				// if (this.fileSize) {
				// 	const isLt = file.size / 1024 / 1024 < this.fileSize;
				// 	if (!isLt) {
				// 	this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
				// 	return false;
				// 	}
				// }
				// this.$modal.loading("正在上传文件，请稍候...");
				return true;
			},
			// 上传成功回调
			handleUploadSuccess(res) {
				console.log('上传成功回调')
				console.log(res)
				//fileName originalFilename
			},
			handleClose() {
				this.dxVisible = false;
				this.hyVisible = false;
				this.smsInfo.smsContent = ""
				this.meetingInfo = {
					status: 0,
					masterId: 0,
					meetingName: "",
					beginTime: "",
					meetingRoomId: "",
					meetingMembers: "",
				}
			},
			// 发送手机短信
			addDx() {
				if (this.selected_user_nums.length == 0) {
					this.$message({
						message: "没有选择人员",
						type: "warning",
					});
					return;
				}
				if (this.smsInfo.smsContent == "") {
					this.$message({
						message: "请填写发送内容",
						type: "warning",
					});
					return;
				}
				this.smsInfo.masterId = this.userId;
				this.smsInfo.receiveMembers = this.selected_user_nums.toString();
				addSendsms(this.smsInfo).then((response) => {
					console.log(response);
					this.$message({
						message: "短信已发送",
						type: "success",
					});
					// this.backRoom();
					this.dxVisible = false
				});
			},
			dxqf() {
				console.log('发送文件 人员等信息到服务器')
				console.log(this.toptitle)
				if(this.toptitle == null){
					this.$message.error('请填写标题')
					return
				}
				const hcontent = this.$refs.myEditor.editor.getHtml() 
				// const htitle = this.$refs.myEditor.title 
				console.log( this.$refs.myEditor)
				this.groupfile.content = hcontent
				this.groupfile.remark = this.toptitle
				this.groupfile.phonenumbers =""
				this.groupfile.userids = ""
				this.groupfile.filename = this.typeKey
				this.groupfile.filepath = ''
				addGroupfiles(this.groupfile).then((res) => {
					console.log(res)
					this.$message({
						message: `发送成功!`,
						type: "success",
					});
					this.fileUpload = false;
					this.getMyGroupFileList()
					this.toptitle = null
				})
				// this.backRoom()
			},
			htmlencode(str) {
				str = str.replace(/&/g, '&amp;');
				str = str.replace(/</g, '&lt;');
				str = str.replace(/>/g, '&gt;');
				str = str.replace(/(?:t| |v|r)*n/g, '<br />');
				str = str.replace(/ /g, '&nbsp; ');
				str = str.replace(/t/g, '&nbsp; &nbsp; ');
				str = str.replace(/x22/g, '&quot;');
				str = str.replace(/x27/g, '&#39;');
				return str;
				},
			dxqf_bk1() {
				console.log('发送文件 人员等信息到服务器')
				const uploadFiles = this.$refs.iupload.uploadFiles
				this.dxVisible = true;
				const filePaths = uploadFiles.map((f) => f.response.fileName)
				const fileNames = uploadFiles.map((f) => f.response.originalFilename)

				this.groupfile.filename = fileNames.toString()
				this.groupfile.filepath = filePaths.toString()
				this.groupfile.phonenumbers = this.selected_user_nums.toString()
				this.groupfile.userids = this.selected_user_ids.toString()
				console.log(this.groupfile)
				addGroupfiles(this.groupfile).then((res) => {
					console.log(res)
					this.$message({
						message: `发送成功!`,
						type: "success",
					});
				})
				this.backRoom()
			},
			cjhy() {
				//弹出层
				this.hyVisible = true;
			},
			backRoom() {
				this.$router.back()
				// this.$router.push({
				// 	path: "/dept",
				// 	query: {
				// 		dept: 203
				// 	},
				// });
			},
			UserSelect(selection) {
				console.log(selection)
				this.selected_user_nums = selection.map((item) => item.phonenumber);
				this.selected_user_ids = selection.map((item) => item.userId);
			},
			UserSelectAll(selection) {
				console.log(selection)
				this.selected_user_nums = selection.map((item) => item.phonenumber);
				this.selected_user_ids = selection.map((item) => item.userId);
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				// this.selected_user_nums = selection.map((item) => item.phonenumber);
				// this.selected_user_ids = selection.map((item) => item.userId);
			},
			handleCancel() {
				this.centerDialogVisible = false;
			},
			//创建会议，后台发送手机短信会议邀请
			handleSendRequest() {
				if (this.selected_user_nums.length == 0) {
					this.$message({
						message: "没有选择人员",
						type: "warning",
					});
					return;
				}
				if (
					this.meetingInfo.meetingName == "" ||
					this.meetingInfo.beginTime == ""
				) {
					this.$message({
						message: "请填写会议主题和时间",
						type: "warning",
					});
					return;
				}
				this.meetingInfo.masterId = this.userId;
				this.selected_user_nums.push(this.userObj.phonenumber); //把自己加入会议人员名单
				this.meetingInfo.meetingMembers = this.selected_user_nums.toString();
				this.meetingInfo.meetingRoomId = this.randomRoomNum();
				addMeeting(this.meetingInfo).then((response) => {
					console.log(response);
					this.$message({
						message: "已通过短信发送会议邀请",
						type: "success",
					});
					// this.backRoom();
				});
			},
			randomRoomNum() {
				return Math.floor(Date.now() / 1000)
			},
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getUserList();
			},
			/** 查询用户列表 */
			getUserList() {
				if (this.queryParams.deptId) {
					//
				} else {
					this.queryParams.deptId = this.deptId
				}
				listUser(this.queryParams).then((response) => {
					this.userList = response.rows;
					this.total = response.total;
					this.toggleSelection()
				});
			},
			// treeCheck(nodeObj, selectObj) {
			treeCheck(data) {
				this.deptType = false;
				if (this.currentCheckData.id === data.id) {
					this.currentCheckData = {};
					this.$refs.tree.setCheckedKeys([]);
				} else {
					this.currentCheckData = data;
					this.$refs.tree.setCheckedKeys([data.id]);
				}
				this.queryParams.deptId = this.currentCheckData.id;
				this.getUserList();
			},
			loadTreedata() {},
			handleRemove(file, fileList) {
				console.log(file);
				console.log(fileList);
			},
			handlePreview(file) {
				console.log(file);
			},
			handleExceed(files, fileList) {
				this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
			},
			beforeRemove(file, fileList) {
				// return this.$confirm(`确定移除 ${ file.name }？`);
			}
		},
	};
</script>
<style scoped>
	::-webkit-scrollbar {
		/*高宽分别对应横竖滚动条的尺寸*/
		width: 10px;
		background-color: rgba(255, 255, 255, 0.1);
	}

	.app-container {
		/* background-color: #ffffff;
		height: calc(100% - 200px);
		overflow-x: hidden; */
		/* border-radius: 20px; */
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.video-box {
		overflow-x: hidden;
		height: calc(100vh - 230px);
	}

	.video-box div {
		float: left;
	}

	.video-box .all {
		border: 1px solid #ccc;
		width: calc(310px - 20px);
		margin: 10px;
		padding: 20px;
		border-radius: 10px;
	}

	.btn-box {
		position: fixed;
		bottom: 20px;
		width: 100%;
		display: flex;
		justify-content: center;
	}

	.index-panel {
		margin: 100px;
		height: calc(100vh - 260px);
		overflow-x: hidden;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.index-panel>div {
		display: flex;
		flex-direction: column;
		width: calc(20% - 40px);
		margin: 20px;
		text-align: center;
		background-image: linear-gradient(to bottom, #ffda81, #fff9c6);
		padding: 30px;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 30px;
		font-size: 26px;
		font-weight: bold;
		color: #f20000;
	}

	.popup-panel {
		margin: 100px;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: calc(100vh - 260px);
		background-color: #ffffff;
		overflow-x: hidden;
		border-radius: 20px;
		padding: 30px
	}

	.top-left {
		position: fixed;
		left: 30px;
		top: 30px;
	}

	.file-list {
		padding-top: 20px;
		flex: 1;
		overflow-x: hidden;
	}

	.file-list .item {
		float: left;
		line-height: 80px;
		text-align: center;
		display: flex;
		flex-direction: column;
		margin: 10px;
		width: calc(20% - 20px);
		border: 1px solid #cccccc;
		padding: 10px 20px;
		border-radius: 10px;
	}
</style>
